<script setup>
import { ref, watchEffect } from "vue";
import * as echarts from "echarts";
import { assign } from "lodash-es";

const props = defineProps({
  label: {
    type: String,
    default: "",
  },
  value: {
    type: Number,
    default: 0,
  },
  sum: {
    type: Number,
    default: 100,
  },
  unit: {
    type: String,
    default: "%",
  },
  grid: {
    type: Object,
    default: {
      left: 26,
      bottom: 5,
      top: 4,
      right: 65,
    },
  },
  yAxis: {
    type: Object,
    default: {},
  },
});

const chartRef = ref(null);

watchEffect(() => {
  if (!chartRef.value) return;
  const chart = echarts.init(chartRef.value);
  const option = {
    grid: props.grid,
    xAxis: {
      show: false,
      type: "value",
      max: props.value > props.sum ? props.value : props.sum,
    },
    yAxis: assign(
      {
        type: "category",
        axisTick: "none",
        axisLine: "none",
        show: true,
        position: "right",
        axisLabel: {
          show: true,
          padding: [0, -35, -10, 0],
          // align: "right",
          verticalAlign: "bottom",
          textStyle: {
            color: "#fff",
            fontSize: 14,
            fontWeight: "bold",
          },
          formatter: function (value) {
            return `${value}`;
          },
        },
        data: [props.value],
      },
      props.yAxis
    ),

    series: [
      {
        // 进度
        data: [{ name: props.label, value: props.value }],
        name: props.label,
        type: "bar",
        barWidth: 6,
        showBackground: true,
        backgroundStyle: {
          borderRadius: 0,
          color: "rgba(255,255,255,0.08)",
          borderColor: "#252F3D",
          borderWidth: 0,
          opacity: 1,
        },
        itemStyle: {
          color: {
            x: 1,
            y: 0,
            x2: 0,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "#2DFFF8",
              },
              {
                offset: 1,
                color: "rgba(45,255,248,0.1)",
              },
            ],
          },
          borderRadius: 0,
        },
        label: {
          show: true,
          position: [0, 0],
          fontSize: 10,
          color: "#C9E9F8",
          padding: [0, 0, 0, -26],
          formatter: "{b}",
        },
        emphasis: {
          disabled: true,
        },
        markPoint: {
          symbol:
            "image://",
          symbolSize: [10, 20],
          label: { show: false },
          symbolOffset: [0, 0],
          data: [{ name: "最大值", type: "max" }],
        },
      },
    ],
  };
  chart.setOption(option);
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>
